package com.github.postsanf.yinian.adapter;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.CreateZoneActivity;
import com.github.postsanf.yinian.activity.InviteChooseActivity;
import com.github.postsanf.yinian.activity.LineTimeStatusFristShareActivity;
import com.github.postsanf.yinian.activity.TimeLineStatusFristActivity;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.fragment.HomeAlbumFragment;
import com.github.postsanf.yinian.fragment.MineFragement;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.github.postsanf.yinian.utils.YNUrlHelper;

import java.util.List;

public class AlbumListAdapter extends RecyclerView.Adapter<AlbumListAdapter.ViewHolder> {
    public static final int TYPE_HEADER = 0;
    public static final int TYPE_NORMAL = 1;
    private Context context;
    private List<YNAlbum> datas;
    private View mHeaderView;
    private boolean switchStyle = false;
    public static Resources mResource;
    private HomeAlbumFragment fragment;
    private String groupsnew;

    public AlbumListAdapter(HomeAlbumFragment fragment, Context context, List<YNAlbum> datas, String groupsnew) {
        this.context = context;
        this.fragment = fragment;
        this.datas = datas;
        this.groupsnew = groupsnew;
    }

    public void setResource(Resources mResource) {
        this.mResource = mResource;
    }

    public AlbumListAdapter(HomeAlbumFragment fragment, Context context, List<YNAlbum> datas, boolean switchStyle, String groupsnew) {
        this.context = context;
        this.fragment = fragment;
        this.datas = datas;
        this.switchStyle = switchStyle;
        this.groupsnew = groupsnew;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView item_memorytitle;
        TextView item_members;
        TextView item_time;
        LinearLayout ll_item_album;                            // 列表View
        RelativeLayout ll_item_nonull;
        LinearLayout ll_item_null;
        LinearLayout ll_item_top;
        SimpleDraweeView iv_item_album_bg;                // 组背景图
        TextView tv_album_name;                            // 组名
        TextView tv_album_class;                        // 组性质
        TextView tv_album_users;                        // 组人数
        TextView tv_album_photos;                        // 组相片数
        ImageView iv_home_invite;                        // 邀请按钮
        ImageView icon_album_share;
        TextView tv_home_invite;
        ImageView iv_show_new_status;                    // 新动态提醒
        ImageView iv_show_new_status_huodong;
        ImageView tip_new;

        public ViewHolder(View itemView) {
            super(itemView);
            if (itemView == mHeaderView) return;
            if (!switchStyle) {
                ll_item_album = (LinearLayout) itemView
                        .findViewById(R.id.ll_item_album);
                ll_item_nonull = (RelativeLayout) itemView
                        .findViewById(R.id.ll_item_nonull);
                ll_item_top = (LinearLayout) itemView
                        .findViewById(R.id.ll_item_top);
                ll_item_null = (LinearLayout) itemView
                        .findViewById(R.id.ll_item_null);
                iv_item_album_bg = (SimpleDraweeView) itemView
                        .findViewById(R.id.iv_item_album_bg);
                tv_album_name = (TextView) itemView
                        .findViewById(R.id.tv_album_name);
                tv_album_class = (TextView) itemView
                        .findViewById(R.id.tv_album_class);
                tv_album_users = (TextView) itemView
                        .findViewById(R.id.tv_album_users);
                tv_album_photos = (TextView) itemView
                        .findViewById(R.id.tv_album_photos);
                iv_home_invite = (ImageView) itemView
                        .findViewById(R.id.iv_home_invite);
                icon_album_share = (ImageView) itemView
                        .findViewById(R.id.icon_album_share);
                iv_show_new_status = (ImageView) itemView.findViewById(R.id.iv_show_new_status_tip);
                iv_show_new_status_huodong = (ImageView) itemView.findViewById(R.id.iv_show_new_status_huodong);
                tip_new = (ImageView) itemView.findViewById(R.id.tip_new);
                tv_home_invite = (TextView) itemView
                        .findViewById(R.id.tv_home_invite);
                item_members = ((TextView) itemView.findViewById(R.id.item_members));
                item_time = ((TextView) itemView.findViewById(R.id.item_time));
                item_memorytitle = ((TextView) itemView.findViewById(R.id.item_memorytitle));
            } else {
                ll_item_album = (LinearLayout) itemView
                        .findViewById(R.id.ll_item_album_else);
                iv_item_album_bg = (SimpleDraweeView) itemView
                        .findViewById(R.id.iv_item_album_bg_else);
                tv_album_name = (TextView) itemView
                        .findViewById(R.id.tv_album_name_else);
                tv_album_class = (TextView) itemView
                        .findViewById(R.id.tv_album_class_else);
                tv_album_users = (TextView) itemView
                        .findViewById(R.id.tv_album_users_else);
                tv_album_photos = (TextView) itemView
                        .findViewById(R.id.tv_album_photos_else);
                iv_home_invite = (ImageView) itemView
                        .findViewById(R.id.iv_home_invite_else);
                item_members = ((TextView) itemView.findViewById(R.id.item_members));
                item_time = ((TextView) itemView.findViewById(R.id.item_time));
                item_memorytitle = ((TextView) itemView.findViewById(R.id.item_memorytitle));
                iv_show_new_status = (ImageView) itemView.findViewById(R.id.iv_show_new_status_tip_else);
                tv_home_invite = (TextView) itemView
                        .findViewById(R.id.tv_home_invite_else);
            }
        }

        public void bindData(final YNAlbum listItems, final int pos) {
            if (listItems != null) {
                if (listItems.getGpic().equals("空图创建")) {
                    ll_item_nonull.setVisibility(View.GONE);
                    ll_item_top.setVisibility(View.GONE);
                    iv_show_new_status_huodong.setVisibility(View.GONE);
                    ll_item_null.setVisibility(View.VISIBLE);
                    ll_item_album.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            context.startActivity(new Intent(context, CreateZoneActivity.class));
                        }
                    });
                    ll_item_album.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            context.sendBroadcast(new Intent("isCantrag").putExtra("isCantrag", false));
                            return true;
                        }
                    });
                } else {
                    ll_item_top.setVisibility(View.GONE);
                    ll_item_null.setVisibility(View.GONE);
                    ll_item_nonull.setVisibility(View.VISIBLE);
                    ImageOptHelper.showFrescoHome(Uri.parse(YNUrlHelper.getHomeImgUrl(context, listItems.getGpic())), iv_item_album_bg, context);
                    item_memorytitle.setText(listItems.getGname());
                    tv_album_class.setText(listItems.getGtype());
                    tv_album_users.setText(listItems.getGnum());
                    tv_album_photos.setText(String.valueOf(listItems.getGpicnum()));
                    if (!StringUtils.isEmpty(listItems.getGeventnum())) {
                        item_time.setText(listItems.getGeventnum());
                    } else {
                        item_time.setText("0");
                    }
                    if (listItems.isHuoDong()) {
//                    if (pos == 0) {
                        iv_show_new_status_huodong.setVisibility(View.VISIBLE);
                        item_members.setText("...");
                        ll_item_album.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                context.startActivity(new Intent(context, TimeLineStatusFristActivity.class).putExtra("StatusFrist", listItems));
                            }
                        });
                        ll_item_album.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                context.sendBroadcast(new Intent("isCantrag").putExtra("isCantrag", false));
                                return true;
                            }
                        });
                    } else {
                        iv_show_new_status_huodong.setVisibility(View.GONE);
//                     iv_show_new_status.setVisibility(listItems.getGmnotify() == 1 ? View.VISIBLE : View.GONE);
                        item_members.setText(listItems.getGnum());
                        ll_item_album.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                iv_show_new_status.setVisibility(View.GONE);
                                YNSingleton.getInstance().setCurAlbum(listItems);
                                ((BaseApplication) context.getApplicationContext()).setCurGid(listItems.getGroupid());
                                context.sendBroadcast(new Intent(ACTIONs.actionUpdateFristAlbum).putExtra("update", true));
                                context.sendBroadcast(new Intent(ACTIONs.actionToPeopleTimeLine));
                                listItems.setGmnotify(0);
                                tip_new.setVisibility(View.GONE);
                                SpUtils.put(context, String.valueOf(listItems.getGroupid()), false);

                            }
                        });
                        iv_home_invite.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                YNSingleton.getInstance().setCurAlbum(listItems);
                                Intent intent = new Intent(context, InviteChooseActivity.class);
                                intent.putExtra(CommonConstants.YNDATAS, listItems);
                                context.startActivity(intent);
                            }
                        });
                        ll_item_album.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                //  fragment.startActivityForResult(new Intent(context, SortActivity.class),CommonConstants.REQ_SORT);
                                context.sendBroadcast(new Intent("isCantrag").putExtra("isCantrag", true));
                                return false;
                            }
                        });
                    }
                    ObjectAnimator scaleX = ObjectAnimator.ofFloat(ll_item_album, "scaleX", 0.3f, 1.0f);
                    ObjectAnimator scaleY = ObjectAnimator.ofFloat(ll_item_album, "scaleY", 0.3f, 1.0f);
                    AnimatorSet animatorSet = new AnimatorSet();
                    animatorSet.playTogether(scaleX, scaleY);
                    animatorSet.setDuration(500);
                    animatorSet.start();
//                EMConversation conversation = EMClient.getInstance().chatManager().getConversation(listItems.getGimid(), EMConversation.EMConversationType.GroupChat);
//                if (conversation == null)
//                    return;
//                int UnreadMsgCount = conversation.getUnreadMsgCount();
//                if (UnreadMsgCount > 0) {
//                    tip_new.setVisibility(View.VISIBLE);
//                } else {
//                    tip_new.setVisibility(View.GONE);
//                }
//                Log.i("xjs", "ggggg===>" + groupsnew);
//                Log.i("xjs", "listItems.getGroupid()===>" + listItems.getGroupid());
                    if (!StringUtils.isEmpty(groupsnew)) {
                        if (groupsnew.contains(",")) {
                            if (checkExist(groupsnew, String.valueOf(listItems.getGroupid()))) {
                                if (SpUtils.getBoolean(context, String.valueOf(listItems.getGroupid()))) {
//                                    tip_new.setVisibility(View.VISIBLE);
                                    iv_show_new_status.setVisibility(View.VISIBLE);
                                } else {
//                                    tip_new.setVisibility(View.GONE);
                                    iv_show_new_status.setVisibility(View.GONE);
                                }
                            } else {
//                                tip_new.setVisibility(View.GONE);
                                iv_show_new_status.setVisibility(View.GONE);
                            }
                        } else {
                            if (String.valueOf(listItems.getGroupid()).equals(groupsnew)) {
                                if (SpUtils.getBoolean(context, String.valueOf(listItems.getGroupid()))) {
//                                    tip_new.setVisibility(View.VISIBLE);
                                    iv_show_new_status.setVisibility(View.VISIBLE);
                                } else {
//                                    tip_new.setVisibility(View.GONE);
                                    iv_show_new_status.setVisibility(View.GONE);
                                }
                            } else {
//                                tip_new.setVisibility(View.GONE);
                                iv_show_new_status.setVisibility(View.GONE);
                            }
                        }
                    } else {
//                        tip_new.setVisibility(View.GONE);
                        iv_show_new_status.setVisibility(View.GONE);
                    }
                    icon_album_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String url = "http://wx.zhuiyinanian.com/app/lookPhotoWall.html?code=";
                            String sec = null;
                            try {
                                sec = YNInviteSecret.encryptDES("groupid=" + listItems.getGroupid(), context.getResources().getString(R.string.UNKNOW_ID));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            url = url + sec + "&fromUserID=" +  ((BaseApplication) context.getApplicationContext()).getCurID()
                                    + "&fromSpaceID=" + sec
                                    + "&port=App空间分享";
                            Intent sintent = new Intent(context, LineTimeStatusFristShareActivity.class);
                            sintent.putExtra("UrlShare", url);
                            sintent.putExtra("title", listItems.getGname() + "    " + MineFragement.nickname + "丨忆年，分享生活记录美好");
                            sintent.putExtra("desc", "和你一起分享我相册中的照片！Brief is life，but love is long.");
                            sintent.putExtra("avatarPaths", listItems.getGpic());
                            context.startActivity(sintent);
                        }
                    });
                }
            }
        }
    }

    public boolean checkExist(String groupsnew, String groupid) {
        String[] ggsnew = groupsnew.split(",");
        for (int i = 0; i < ggsnew.length; i++) {
            if (groupid.equals(ggsnew[i])) {
                return true;
            }
        }
        return false;
    }


    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
        notifyItemInserted(0);
    }

    public View getHeaderView() {
        return mHeaderView;
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderView == null) return TYPE_NORMAL;
        if (position == 0) return TYPE_HEADER;
        return TYPE_NORMAL;
    }

    private YNAlbum getItem(int position) {
        return datas.get(position);
    }

    // 创建ViewHolder
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER) return new ViewHolder(mHeaderView);
        View convertView = LayoutInflater.from(parent.getContext()).inflate(switchStyle ? R.layout.yn_item_album_else : R.layout.yn_item_album, parent, false);
        return new ViewHolder(convertView);
    }

    // 绑定数据到View
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_HEADER) return;
        final int pos = getRealPosition(holder);
        YNAlbum listItems = getItem(pos);
//        holder.setIsRecyclable(false);
        holder.bindData(listItems, pos);
        holder.itemView.setTag(listItems);
    }


    public int getRealPosition(RecyclerView.ViewHolder holder) {
        int position = holder.getLayoutPosition();
        return mHeaderView == null ? position : position - 1;
    }

    @Override
    public int getItemCount() {
        return mHeaderView == null ? datas.size() : datas.size() + 1;
    }

//    @Override
//    public void onItemMove(int from, int to) {
//
//        from = from<=0?0:from-1;
//        to = to>=datas.size()?datas.size()-1:to-1;
//
//        YNAlbum item = datas.get(from);
//        datas.remove(from);
//        datas.add(to , item);
//        notifyItemMoved(from, to);
////        Collections.swap(datas, from, to);
////        notifyItemMoved(from, to);
//        fragment.updateList(getIdList());
//    }

//    @Override
//    public void onItemMove(int fromPosition, int toPosition) {
//        YNAlbum item = datas.get(fromPosition);
//        datas.remove(fromPosition);
//        datas.add(toPosition, item);
//        notifyItemMoved(fromPosition, toPosition);
//    }

//    private String getIdList() {
//        List<String> res = new ArrayList<>();
//        for (int i = 0; i < datas.size(); i++) {
//            res.add(datas.get(i).getGroupid() + "");
//        }
//        return res.toString();
//    }
}
